/*
 * Copyright 2020 www.mytijian.com All right reserved. This software is the
 * confidential and proprietary information of www.mytijian.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with www.mytijian.com.
 */
package com.mytijian.task.lifecycle;

import java.util.Collection;
import java.util.Comparator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class ApplicationLifycycleContainer {
    protected static Map<Class, ApplicationLifycycle> map = new ConcurrentHashMap<>();
    public static void put(Class<? extends ApplicationLifycycle> clazz, ApplicationLifycycle applicationLifycycle) {
        map.put(clazz, applicationLifycycle);

    }
    static {
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                ApplicationLifycycleContainer.destoryAll();
                ApplicationLifycycleContainer.map.clear();
            }
        }));
    }
    public static void initAll() {
        Collection<ApplicationLifycycle> collection = map.values().stream().sorted(Comparator.comparing(ApplicationLifycycle::initSort)).collect(Collectors.toList());
        for (ApplicationLifycycle applicationLifycycle : collection) {
            applicationLifycycle.init();
        }
    }
    public static void destoryAll() {
        Collection<ApplicationLifycycle> collection = map.values().stream().sorted(Comparator.comparing(ApplicationLifycycle::destorySort)).collect(Collectors.toList());
        for (ApplicationLifycycle applicationLifycycle : collection) {
            applicationLifycycle.destory();
        }
    }
}
